package sample;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.google.gson.Gson;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class Controller {


    @FXML
    private Button selectFile;
    @FXML
    private Label filePath;

    public void selectOrderFile(ActionEvent event) {
        System.out.println("开始选择订单文件.");
        Node source = (Node) event.getSource();
        Window window = source.getScene().getWindow();

        File file = selectFile((Stage) window);

        if (file != null) {
            String absolutePath = file.getAbsolutePath();
            filePath.setText(absolutePath);
            startTransfer(file);
        } else {
            System.out.println("未选中任何点单文件.");
        }

    }

    /**
     * 转换订单
     *
     * @param file 订单文件
     */
    private void startTransfer(File file) {
        System.out.println("开始转换.");
        // 设定UTF-8字符集，使用带缓冲区的字符输入流BufferedReader读取文件内容
        try {
            List<String[]> result = new ArrayList<>();
            FileInputStream fileInputStream = new FileInputStream(file);
            ReadCSV(fileInputStream, result);

            Map<String, Map<String, List<Order>>> orderMap = result.stream().map(
                    record ->
                    {
                        String type = record[10].trim();//菜品类型 1.豆制品,2.蔬菜类,3.菌菇类,4.面食类
                        String name = record[9].trim();//菜品名称
                        int number = Integer.parseInt(record[12].trim());//商品数量
                        String remarks = "";//订单备注
                        if (record.length >= 42) {
                            remarks = record[42].trim();
                        }
                        return new Order(type, name, number, remarks);
                    }
            ).collect(Collectors.groupingBy(Order::getType, Collectors.groupingBy(Order::getName)));

            Gson gson = new Gson();
            System.out.println(gson.toJson(orderMap));
            List<String[]> content = new ArrayList<>();
            sortMapByKey(orderMap).forEach(
                    (type, map) -> {
                        map.forEach(
                                (name, list) -> {
                                    String[] record = new String[4];
                                    AtomicInteger total= new AtomicInteger();
                                    String collect = list.stream()
                                            .sorted(Comparator.comparing(Order::getNumber))
                                            .map(
                                                    order -> {
                                                        int number = order.getNumber();
                                                        total.addAndGet(number);
                                                        return String.valueOf(number);
                                                    }
                                            ).collect(Collectors.joining(" + "));
                                    record[0] = type;
                                    record[1] = name;
                                    record[3] = collect;
                                    record[2] = total.toString();
                                    content.add(record);
                                }
                        );
                    }
            );

            WriteCSV(getOutName(file), content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private File selectFile(Stage stage) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("订单文件", "*.csv"));
        fileChooser.setTitle("选择订单文件");
        return fileChooser.showOpenDialog(stage);
    }

    private String getOutName(File input) {
        String out = input.getAbsolutePath().replace(".csv", "采购单.csv");
        System.out.println(out);
        return out;
    }

    private void ReadCSV(FileInputStream fileInputStream, List<String[]> result) throws IOException {

        CsvReader reader = new CsvReader(fileInputStream, ',', Charset.forName("gb2312"));
        reader.readHeaders();
        while (reader.readRecord()) {
            result.add(reader.getValues());
        }
        reader.close();
//        for (int row = 0;row < result.size(); row++) {
//            int Length=result.get(row).length;
//            if(Length > 0){
//                for(int i=0;i<Length;i++){
//                    System.out.print(result.get(row)[i]+","+"["+i+"]");
//                }//for
//
//            }//if
//            System.out.println("");
//        }//for

    }//class

    private void WriteCSV(String path, List<String[]> content) throws IOException {

        File out = new File(path);
        if (!out.exists()) {
            boolean newFile = out.createNewFile();
            if (!newFile) {
                System.out.println("创建文件失败");
                System.exit(0);
            }
        }

        try {
            CsvWriter csvWriter = new CsvWriter(path, ',', Charset.forName("gb2312"));

            // 写表头和内容
//            csvWriter.writeRecord(headers);
            for (int i = 0; i < content.size(); i++) {
                String[] line = content.get(i);
                csvWriter.writeRecord(line);
            }

            // 关闭csvWriter
            csvWriter.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(0);
        }
    }
    /**
     *
     * <b>Description:</b><br>对map利用key进行排序
     * @param map
     * @return
     * @Note
     * <b>Author:</b> 简陌刀丶阿吉
     * <br><b>Date:</b> 2019年8月27日 上午11:06:32
     * <br><b>Version:</b> 1.0
     */
    public static Map<String, Map<String, List<Order>>> sortMapByKey(Map<String, Map<String, List<Order>>> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Map<String, List<Order>>> sortMap = new TreeMap<String, Map<String, List<Order>>>(new KeyCompareUtil());
        sortMap.putAll(map);
        return sortMap;
    }
    public static class KeyCompareUtil implements Comparator<String>{
        /**
         *
         *  从小到大排序
         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
         */
        @Override
        public int compare(String s1, String s2) {
            return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
        }
    }

}
